package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private TextView selectedMovieText;
    private MovieAdapter adapter;
    private List<Movie> movieList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化视图
        listView = findViewById(R.id.list_movie);
        selectedMovieText = findViewById(R.id.selected_movie_text);

        // 初始化数据
        initData();

        // 设置适配器
        adapter = new MovieAdapter(this, R.layout.item_movie, movieList);
        listView.setAdapter(adapter);

        // 设置列表项点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Movie movie = movieList.get(position);
                openMovieDetail(movie);
            }
        });
    }

    private void initData() {
        movieList = new ArrayList<>();
        movieList.add(new Movie(R.drawable.movie1, "《肖申克的救赎》", "这部电影讲述了银行家安迪因被误判为枪杀妻子及其情人的罪名入狱后，他不动声色、步步为营地谋划自我拯救并最终成功越狱，重获自由的故事。"));
        movieList.add(new Movie(R.drawable.movie2, "《教父》", "讲述了以维托·唐·柯里昂为首的黑帮家族的发展过程以及柯里昂的小儿子迈克如何接任父亲成为黑帮首领的故事。"));
        movieList.add(new Movie(R.drawable.movie3, "《泰坦尼克号》", "影片以1912年泰坦尼克号邮轮在其处女启航时触礁冰山而沉没的事件为背景，讲述了处于不同阶层的两个人穷画家杰克和贵族女露丝抛弃世俗的偏见坠入爱河，最终杰克把生存的机会让给了露丝的感人故事。"));
        movieList.add(new Movie(R.drawable.movie4, "《星球大战》", "讲述了一个发生在遥远星系的史诗级故事，涉及原力、绝地武士、银河帝国与反抗军之间的斗争。"));
        movieList.add(new Movie(R.drawable.movie5, "《复仇者联盟》", "来自钢铁侠、美国队长、雷神等超级英雄集结在一起，共同对抗强大的反派灭霸的故事。"));
    }

    private void openMovieDetail(Movie movie) {
        Intent intent = new Intent(this, MovieDetailActivity.class);
        intent.putExtra("movie_title", movie.getTitle());
        intent.putExtra("movie_description", movie.getDescription());
        intent.putExtra("movie_image", movie.getImageResourceId());
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            String selectedMovie = data.getStringExtra("selected_movie");
            selectedMovieText.setText("您选择的电影是: " + selectedMovie);
        }
    }
}    